// 全局变量
let timer = null;
let isRunning = false;
let currentMode = 'work'; // work, short-break, long-break
let timeLeft = 25 * 60; // 默认25分钟工作时间（秒）
let totalSeconds = timeLeft;
let completedPomodoros = 0;
let totalFocusTime = 0;
let sessionStartTime = null;

// DOM元素
const timeLeftEl = document.querySelector('.time-left');
const currentModeEl = document.querySelector('.current-mode');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
const modeBtns = document.querySelectorAll('.mode-btn');
const progressBar = document.querySelector('.progress-bar');
const timerDisplay = document.querySelector('.timer-display');
const notificationSound = document.getElementById('notificationSound');
const completedPomodorosEl = document.getElementById('completedPomodoros');
const totalFocusTimeEl = document.getElementById('totalFocusTime');
const efficiencyRateEl = document.getElementById('efficiencyRate');
const workDurationInput = document.getElementById('workDuration');
const shortBreakDurationInput = document.getElementById('shortBreakDuration');
const longBreakDurationInput = document.getElementById('longBreakDuration');
const autoStartBreakCheckbox = document.getElementById('autoStartBreak');
const autoStartWorkCheckbox = document.getElementById('autoStartWork');
const applySettingsBtn = document.getElementById('applySettingsBtn');

// 配置
let settings = {
    workDuration: 25,
    shortBreakDuration: 5,
    longBreakDuration: 15,
    autoStartBreak: true,
    autoStartWork: true
};

// 初始化
function init() {
    // 加载本地存储的设置和统计数据
    loadData();
    
    // 计算圆环周长
    const circumference = 2 * Math.PI * 130; // 半径130px
    progressBar.style.strokeDasharray = circumference;
    progressBar.style.strokeDashoffset = 0;
    
    // 更新显示
    updateTimerDisplay();
    updateStatsDisplay();
    
    // 添加事件监听
    setupEventListeners();
    
    // 请求通知权限
    requestNotificationPermission();
}

// 设置事件监听
function setupEventListeners() {
    // 控制按钮
    startBtn.addEventListener('click', startTimer);
    pauseBtn.addEventListener('click', pauseTimer);
    resetBtn.addEventListener('click', resetTimer);
    
    // 模式切换
    modeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            changeMode(btn.dataset.mode);
        });
    });
    
    // 设置应用
    applySettingsBtn.addEventListener('click', applySettings);
    
    // 键盘快捷键
    document.addEventListener('keydown', handleKeyPress);
}

// 开始计时器
function startTimer() {
    if (!isRunning) {
        isRunning = true;
        startBtn.disabled = true;
        pauseBtn.disabled = false;
        sessionStartTime = Date.now();
        
        timer = setInterval(() => {
            timeLeft--;
            updateTimerDisplay();
            updateProgressBar();
            
            // 时间结束
            if (timeLeft <= 0) {
                timerComplete();
            }
            
            // 最后10秒提醒
            if (timeLeft === 10) {
                playNotification();
                timerDisplay.classList.add('pulse');
            }
        }, 1000);
    }
}

// 暂停计时器
function pauseTimer() {
    if (isRunning) {
        isRunning = false;
        clearInterval(timer);
        startBtn.disabled = false;
        pauseBtn.disabled = true;
        
        // 记录已工作时间
        if (currentMode === 'work') {
            const sessionTime = Math.floor((Date.now() - sessionStartTime) / 1000);
            totalFocusTime += sessionTime;
            saveStats();
            updateStatsDisplay();
        }
        
        timerDisplay.classList.remove('pulse');
    }
}

// 重置计时器
function resetTimer() {
    pauseTimer();
    timeLeft = totalSeconds;
    updateTimerDisplay();
    updateProgressBar();
    timerDisplay.classList.remove('pulse');
}

// 计时器完成
function timerComplete() {
    pauseTimer();
    playNotification();
    showNotification(`${getModeName(currentMode)}时间结束！`);
    
    // 如果是工作模式完成，增加统计
    if (currentMode === 'work') {
        completedPomodoros++;
        totalFocusTime += totalSeconds;
        saveStats();
        updateStatsDisplay();
        
        // 自动开始休息
        if (settings.autoStartBreak) {
            // 每4个番茄钟后进行一次长休息
            if (completedPomodoros % 4 === 0) {
                setTimeout(() => changeMode('long-break'), 1000);
            } else {
                setTimeout(() => changeMode('short-break'), 1000);
            }
        }
    } else {
        // 休息结束，自动开始工作
        if (settings.autoStartWork) {
            setTimeout(() => changeMode('work'), 1000);
        }
    }
}

// 切换模式
function changeMode(mode) {
    // 停止当前计时器
    pauseTimer();
    
    // 更新模式状态
    currentMode = mode;
    
    // 更新按钮样式
    modeBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.mode === mode) {
            btn.classList.add('active');
        }
    });
    
    // 设置时间和样式
    switch (mode) {
        case 'work':
            timeLeft = settings.workDuration * 60;
            totalSeconds = timeLeft;
            currentModeEl.textContent = '工作时间';
            progressBar.style.stroke = '#ff6b6b';
            timerDisplay.classList.remove('short-break', 'long-break');
            timerDisplay.classList.add('work');
            break;
        case 'short-break':
            timeLeft = settings.shortBreakDuration * 60;
            totalSeconds = timeLeft;
            currentModeEl.textContent = '短休息';
            progressBar.style.stroke = '#48dbfb';
            timerDisplay.classList.remove('work', 'long-break');
            timerDisplay.classList.add('short-break');
            break;
        case 'long-break':
            timeLeft = settings.longBreakDuration * 60;
            totalSeconds = timeLeft;
            currentModeEl.textContent = '长休息';
            progressBar.style.stroke = '#10ac84';
            timerDisplay.classList.remove('work', 'short-break');
            timerDisplay.classList.add('long-break');
            break;
    }
    
    // 更新显示
    updateTimerDisplay();
    updateProgressBar();
}

// 获取模式名称
function getModeName(mode) {
    switch (mode) {
        case 'work': return '工作';
        case 'short-break': return '短休息';
        case 'long-break': return '长休息';
        default: return '';
    }
}

// 更新计时器显示
function updateTimerDisplay() {
    const minutes = Math.floor(timeLeft / 60).toString().padStart(2, '0');
    const seconds = (timeLeft % 60).toString().padStart(2, '0');
    timeLeftEl.textContent = `${minutes}:${seconds}`;
}

// 更新进度条
function updateProgressBar() {
    const circumference = 2 * Math.PI * 130;
    const offset = circumference - (timeLeft / totalSeconds) * circumference;
    progressBar.style.strokeDashoffset = offset;
}

// 播放通知音效
function playNotification() {
    try {
        notificationSound.currentTime = 0;
        notificationSound.play();
    } catch (e) {
        console.log('无法播放音效:', e);
    }
}

// 显示浏览器通知
function showNotification(message) {
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('番茄时钟', {
            body: message,
            icon: 'https://cdn-icons-png.flaticon.com/512/3281/3281657.png',
            tag: 'pomodoro-timer',
            vibrate: [200, 100, 200]
        });
    }
}

// 请求通知权限
function requestNotificationPermission() {
    if ('Notification' in window && Notification.permission !== 'denied') {
        Notification.requestPermission();
    }
}

// 应用设置
function applySettings() {
    settings = {
        workDuration: parseInt(workDurationInput.value) || 25,
        shortBreakDuration: parseInt(shortBreakDurationInput.value) || 5,
        longBreakDuration: parseInt(longBreakDurationInput.value) || 15,
        autoStartBreak: autoStartBreakCheckbox.checked,
        autoStartWork: autoStartWorkCheckbox.checked
    };
    
    // 保存设置
    localStorage.setItem('pomodoroSettings', JSON.stringify(settings));
    
    // 如果当前模式被更改，更新计时器
    switch (currentMode) {
        case 'work':
            if (timeLeft === totalSeconds) { // 只有在未开始的情况下才更新
                changeMode('work');
            }
            break;
        case 'short-break':
            if (timeLeft === totalSeconds) {
                changeMode('short-break');
            }
            break;
        case 'long-break':
            if (timeLeft === totalSeconds) {
                changeMode('long-break');
            }
            break;
    }
    
    // 显示应用成功提示
    showToast('设置已应用');
}

// 更新统计显示
function updateStatsDisplay() {
    completedPomodorosEl.textContent = completedPomodoros;
    totalFocusTimeEl.textContent = totalFocusTime;
    
    // 计算完成率（假设每天目标8个番茄钟）
    const targetPomodoros = 8;
    const efficiencyRate = Math.min(100, Math.round((completedPomodoros / targetPomodoros) * 100));
    efficiencyRateEl.textContent = `${efficiencyRate}%`;
}

// 保存统计数据
function saveStats() {
    // 检查是否是新的一天
    const today = new Date().toDateString();
    const lastSavedDate = localStorage.getItem('pomodoroLastSavedDate');
    
    if (lastSavedDate !== today) {
        // 新的一天，重置统计
        completedPomodoros = 0;
        totalFocusTime = 0;
    }
    
    // 保存数据
    localStorage.setItem('pomodoroStats', JSON.stringify({
        completedPomodoros,
        totalFocusTime
    }));
    localStorage.setItem('pomodoroLastSavedDate', today);
}

// 加载设置和统计
function loadData() {
    // 加载设置
    const savedSettings = localStorage.getItem('pomodoroSettings');
    if (savedSettings) {
        settings = JSON.parse(savedSettings);
        workDurationInput.value = settings.workDuration;
        shortBreakDurationInput.value = settings.shortBreakDuration;
        longBreakDurationInput.value = settings.longBreakDuration;
        autoStartBreakCheckbox.checked = settings.autoStartBreak;
        autoStartWorkCheckbox.checked = settings.autoStartWork;
    }
    
    // 加载统计数据
    const today = new Date().toDateString();
    const lastSavedDate = localStorage.getItem('pomodoroLastSavedDate');
    
    if (lastSavedDate === today) {
        const savedStats = localStorage.getItem('pomodoroStats');
        if (savedStats) {
            const stats = JSON.parse(savedStats);
            completedPomodoros = stats.completedPomodoros || 0;
            totalFocusTime = stats.totalFocusTime || 0;
        }
    }
}

// 键盘快捷键处理
function handleKeyPress(e) {
    // 空格键：开始/暂停
    if (e.code === 'Space' && !e.target.matches('input')) {
        e.preventDefault();
        if (isRunning) {
            pauseTimer();
        } else {
            startTimer();
        }
    }
    
    // R键：重置
    if (e.code === 'KeyR' && !e.target.matches('input')) {
        resetTimer();
    }
    
    // 数字键1-3：切换模式
    if (e.code === 'Digit1' && !e.target.matches('input')) {
        changeMode('work');
    }
    if (e.code === 'Digit2' && !e.target.matches('input')) {
        changeMode('short-break');
    }
    if (e.code === 'Digit3' && !e.target.matches('input')) {
        changeMode('long-break');
    }
}

// 显示提示消息
function showToast(message) {
    // 检查是否已有toast，有则移除
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }
    
    // 创建新的toast
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // 添加样式
    toast.style.position = 'fixed';
    toast.style.bottom = '20px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.background = 'rgba(0, 0, 0, 0.7)';
    toast.style.color = 'white';
    toast.style.padding = '10px 20px';
    toast.style.borderRadius = '4px';
    toast.style.zIndex = '1000';
    toast.style.opacity = '0';
    toast.style.transition = 'opacity 0.3s ease';
    
    // 显示toast
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 3秒后隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);

// 页面关闭前保存数据
window.addEventListener('beforeunload', saveStats);